var materialArray;
var baseUrl = "/weixin/";
var table;
//相关业务逻辑
var vueData = {
  loading: false,
  printMode: 'edit',
  orderId: '',
  pageOrderId: '',
  orderList: [],
  diffDay: null,
  filterParams: ['orderId', 'companyOrderId', 'factoryId', 'customerId']
};

$(function () {
  page.bindTag();
  page.removeBtnBind();
  page.remove();
  scheduling.bind();
});

var page = { //页面总变量 
  materialSort: 0,
  searchType: "",
  procedureSumCount: 0,
  aleradySaveData: [],
  bindTag: function () {
    /**
     * 删除工艺结构树
     */
    $("#deleteTreeBtn").bind("click", function () {
      layer.confirm('确定删除此组合？', {
        btn: ['删除', '取消'] //按钮
      }, function () {
        ajaxUtil.ajaxRuquest(baseUrl + "partsProcedure/deleteTree", {
          "orderId": vueData.pageOrderId
        }, function (data) {
          layer.msg(data, {
            icon: 1
          });
          vueData.diffDay = null;
          page.clearCanvas();
          $(".materialProcedure").html("");
        });
      });
    });

    /**
     * 打印
     */
    $("#printBtn").bind("click", function () {
      $(".title").hide();
      page.setOrderDetail();
      vueData.printMode = 'print';

      app.$nextTick(function () {
        window.print();
        $(".title").show();
        $(".print").html("");
        vueData.printMode = 'edit';
      });
    });

    /**
     * 保存
     */
    $("#saveBtn").bind("click", function () {
      page.saveOrderMaterialProcedure();
    });

    /**
     *  查询已保存的订单工序
     */
    $("#queryBtn").bind("click", function () {
      var orderId = vueData.orderId.trim();
      if (orderId == '') {
        layAlert("请输入或选择订单编号");
        return false;
      }
      page.getAlreadySaveProcedure(orderId);
    });

    /**
     * 根据订单编号查询工序
     */
    $("#queryOrderMaterialProcedureBtn").bind("click", function () {
      page.getOrderMaterialProcedure();
    });

    /**
     * 编辑工序
     */
    $("#editMaterialProcedureBtn").bind("click", function () {
      $("#setCombinationModal .left-box").html("");
      $("#setCombinationModal .right-box").html("");
      page.editMaterialProcedure();
    });

    /**
     * 选择物料类型
     */
    $("#materialType").bind("change", function () {
      var materialType = $(this).val();
      if (materialType == '') {
        layAlert("请选择物料类型");
        $("#setCombinationModal .item-box").html("");
        return false;
      }
      page.getOrderMaterialProcedureHaveAndNoHave();
    });

    /**
     * 搜索
     */
    $("#setSearchWhereBtn").bind("click", function () {
      page.getOrderMaterialNoHave();
    });

    /**
     * 保存修改的工序 
     */
    $("#setCombinationModalBtn").bind("click", function () {
      page.saveUpdateProcedure();
    });

    /**
     * 导出为excle
     */
    $("#exportExcleBtn").bind("click", function () {
      var pageOrderId = vueData.pageOrderId;
      if (pageOrderId == '') {
        layAlert("未获取到排序或查询的单号");
        return false;
      }
      var url = baseUrl + "partsProcedure/downlodeOrderPrucedureData?orderId=" + pageOrderId;
      tableUtil.download(url);
    });
  },
  setOrderDetail: function () {
    var pageOrderId = vueData.pageOrderId;
    if (pageOrderId == '') {
      return false;
    }
    var orderList = vueData.orderList;
    if (orderList.length <= 0) {
      return false;
    }
    for (var i = 0; i < orderList.length; i++) {
      var order = orderList[i];
      if (order.orderId === pageOrderId) {
        var html = "工厂型号：" + order.factoryId + " 订单编号：" + order.companyOrderId;
        $(".print").html(html);
      }
    }
  },
  /**
   * 获取订单物料工序
   */
  getOrderMaterialProcedure: function () {
    var orderId = vueData.orderId.trim();
    var sort = $("#sort option:selected").val();
    if (orderId == '') {
      layAlert("请输入或选择订单编号");
      return false;
    }
    if (sort == '') {
      layAlert("请选择排序方式");
      return false;
    }
    ajaxUtil.ajaxRuquest(baseUrl + "partsProcedure/getOrderMaterialProcedure", {
      "orderId": orderId,
      "sort": sort
    }, function (data) {
      vueData.pageOrderId = data.orderId;
      data = data.combinationList;

      var materialColorArray = new Array();
      var colorIndex = 0;
      //为每一个物料类型设置对应的颜色
      for (var i = 0; i < data.length; i++) {
        if (data[i].gruopId == null || data[i].gruopId == '') {

          var object = new Object();
          object.materialType = data[i].materialType;
          if (colorIndex < config.colorArray.length) {
            object.color = config.colorArray[colorIndex];
          } else {
            object.color = config.colorArray[colorIndex - config.colorArray.length];
          }
          /**
           * 设置将物料顺序设置到工序中
           */
          data[i].proSort = colorIndex;
          var procedureList = data[i].procedureList;
          if (procedureList != null) {
            for (var j = 0; j < data[i].procedureList.length; j++) {
              data[i].procedureList[j].proSort = colorIndex;
              data[i].procedureList[j].color = object.color;
            }
          }
          materialColorArray.push(object);
          colorIndex++;
        }
      }

      var dataCopy = data;
      /**
       * 将组合物料工序与第一个匹配的物料工序合并,合并的颜色以最后一个显示
       */
      for (var i = 0; i < data.length; i++) {
        if (data[i].gruopId != null && data[i].gruopId != '') { //如果是多物料组合的工序
          var gruopId = data[i].gruopId;
          var gruopIdArray = gruopId.split('-'); //多物料组合id数组
          var firstIndex = -1; //保存第一次匹配下标
          var lastIndex = -1;
          var color = "";
          for (var j = 0; j < dataCopy.length; j++) { //遍历原始数据
            //如果遍历的物料有被合并
            if ($.inArray(dataCopy[j].id, gruopIdArray) != -1) {
              if (firstIndex == -1) { //是第一次匹配
                firstIndex = j;
              }
              lastIndex = j;
              if (gruopIdArray.length <= 1) { //最后一次匹配
                color = page.getMaterialColor(dataCopy[j].materialType, materialColorArray);;
                break;
              } else { //移除组合元素
                gruopIdArray.splice($.inArray(dataCopy[j].id, gruopIdArray), 1);
              }
            }
          }
          for (var z = 0; z < data[i].procedureList.length; z++) {
            data[i].procedureList[z].color = color;
            data[i].procedureList[z].proSort = lastIndex;
            dataCopy[firstIndex].procedureList.push(data[i].procedureList[z]);
          }
        }
      }
      data = dataCopy;

      /**
       * 循环遍历物料类型
       */
      var sumCount = 0;
      var $html = $('<div></div>');
      for (var i = 0; i < data.length; i++) {
        var obj = data[i];
        var materialType = obj.materialType;
        if (obj.gruopId === null || obj.gruopId === '') {
          var color = page.getMaterialColor(obj.materialType, materialColorArray);
          var procedureColor = "";
          var procedureList = obj.procedureList;
          procedureList = _.orderBy(procedureList, ['proSort', 'sort'], ['asc', 'asc']);
          if (procedureList == null) {
            procedureList = [];
          }
          sumCount = procedureList.length + sumCount;
          var $item = $('<div class="pro-item"></div>');
          $html.append($item);

          $item.append(`
            <div class="item-title material" style="color:${color};" materialType="${materialType}" color="${color}">
              <span>${materialType}</span>
              <span>${procedureList.length}</span>
            </div>
          `);
          var otherMaching;
          for (var j = 0; j < procedureList.length; j++) {
            var pro = procedureList[j];
            if (pro.otherMaching === '') {
              if (pro.color !== undefined) {
                procedureColor = pro.color;
              } else {
                procedureColor = color;
              }
              otherMaching = '';
            } else {
              procedureColor = page.getMaterialColor(pro.otherMaching, materialColorArray);
              otherMaching = pro.otherMaching;
            }

            $item.append(`
              <div style="color:${procedureColor};" class="procedureFont" color="${procedureColor}" 
                materialType="${materialType}" procedureId="${pro.procedureId}" otherMaching="${otherMaching}">
                ${page.getMaterialProText(pro)}
              </div>
            `);
          }
        }
      }

      page.procedureSumCount = sumCount;
      $(".procedureSumCount").text(page.procedureSumCount);
      //			$html.append(`<div class="pro-item"><div class="item-title">总工序数：${sumCount}</div></div>`);
      $(".materialProcedure").html($html.html());
      $("#editMaterialProcedureBtn").addClass("hidden");
      $("#autoSchedulingBtn").addClass("hidden");
      $("#deleteTreeBtn").addClass("hidden");
      page.drawFlow();
      vueData.diffDay = null;
    });
    page.searchType = "sort";
  },
  getMaterialProText: function (pro) {
    var proText = [pro.workShopName, pro.procedureName];
    var otherMaching = pro.otherMaching;
    if (otherMaching !== '') {
      proText.push(otherMaching);
    }
    proText = proText.join('-');
    var maxLength = 20;
    if (proText.length <= maxLength) {
      return proText;
    }

    var count = Math.ceil(proText.length / maxLength);
    var techProcessName = '';
    for (var i = 0; i < count; i++) {
      var index = i * maxLength;
      var addText = proText.substr(index, maxLength);
      if (i !== count - 1) {
        addText += '<br>';
      }
      techProcessName += addText;
    }

    return techProcessName;
  },
  getMaterialColor: function (materialType, materialColorArray) {
    var color = '';
    for (var i = 0; i < materialColorArray.length; i++) {
      if (materialType == materialColorArray[i].materialType) {
        color = materialColorArray[i].color;
        break;
      }
    }
    return color;
  },
  saveOrderMaterialProcedure: function () {
    var array = new Array();
    var materialSort = 1;

    $(".pro-item").each(function () {
      var sort = 1;
      $(this).find(".procedureFont").each(function () {
        var object = new Object();
        object.maching = $(this).attr("materialType");
        object.id = $(this).attr("procedureId");
        object.otherMaching = $(this).attr("otherMaching");
        object.color = $(this).attr("color");
        object.sort = sort;
        object.materialSort = materialSort;
        array.push(object);
        sort++;
      });
      materialSort++;
    });


    var otherArray = _.map(array, "otherMaching");
    otherArray = _.uniq(otherArray);

    var noHaveCountArray = new Array();
    /**
     * 遍历物料
     */
    $(".material").each(function () {
      var materialType = $(this).attr("materialType");
      if ($.inArray(materialType, otherArray) == -1) {
        noHaveCountArray.push(materialType);
      }
    });

    if (noHaveCountArray.length > 1) {
      var tishi = "";
      for (var key in noHaveCountArray) {
        tishi += noHaveCountArray[key] + "、"
      }
      tishi += "未和其他物料关联，请检查设置";
      layAlert(tishi);
      return false;
    }

    if (array.length <= 0) {
      layAlert("没有配置工序");
      return false;
    }
    ajaxUtil.ajaxRuquest(baseUrl + "partsProcedure/saveOrderMaterialProcedure", {
      "orderId": vueData.pageOrderId,
      "procedureArray": JSON.stringify(array)
    }, function (data) {
      $("#editMaterialProcedureBtn").removeClass("hidden");
      $("#autoSchedulingBtn").removeClass("hidden");
      layer.msg(data, {
        icon: 1
      });
      page.saveProcedureImg();
    });
  },
  saveProcedureImg: function () {
    $(".title").hide();
    $(".page-container").addClass('save-img');
    page.setOrderDetail();
    vueData.printMode = 'print';
    var index = layer.load(1, {
      shade: [0.1, '#fff']
    });
    app.$nextTick(function () {
      page.toSaveProcedureImg().then(function () {
        $(".title").show();
        $(".page-container").removeClass('save-img');
        $(".print").html("");
        vueData.printMode = 'edit';
        layer.close(index);
      });
    });
  },
  toSaveProcedureImg: function () {
    return page.postImg().then(function (imgUrl) {
      return ajaxRequest('fileManager/uploadFileForPrint', {
        order_no: vueData.pageOrderId,
        type: 8,
        file_name: '订单配件工艺-' + moment().format('YYYY-MM-DD'),
        url: imgUrl
      }).then(function () {
        return imgUrl;
      });
    }).catch(function () {
      return null;
    });
  },
  postImg: function () {
    var el = $('.page-container')[0];
    return new Promise(function (resole, reject) {
      domtoimage.toBlob(el, {
        bgcolor: '#ffffff',
        quality: 1
      }).then(function (blob) {
        var file = {
          name: '订单配件工艺',
          blob: blob
        };
        postImgsToQiniu('fileManager/getQiniuToken', file).then(function (imgUrl) {
          imgUrl = imgUrl[0];
          resole(imgUrl);
        }).catch(function (error) {
          reject(error);
        });
      }).catch(function (error) {
        reject(error);
      });
    });
  },
  getAlreadySaveProcedure: function (orderId) {
    vueData.pageOrderId = orderId;
    ajaxUtil.ajaxRuquest(baseUrl + "partsProcedure/getAlreadySaveProcedure", {
      "orderId": orderId
    }, function (data) {
      page.aleradySaveData = data;
      if (data.length <= 0) {
        layAlert("该订单没有设置工序");
        return false;
      }
      /**
       * 循环遍历物料类型
       */
      var sumCount = 0;
      var $html = $('<div></div>');
      for (var i = 0; i < data.length; i++) {
        var obj = data[i];
        var procedureList = obj.procedureList;
        var materialType = obj.materialType;
        var color = procedureList[0].color;
        var $item = $('<div class="pro-item"></div>');
        $html.append($item);

        $item.append(`
            <div class="item-title material" style="color:${color};" materialType="${materialType}" color="${color}">
              <span>${materialType}</span>
              <span>${procedureList.length}</span>
            </div>
          `);
        sumCount = sumCount + procedureList.length;
        for (var j = 0; j < procedureList.length; j++) {
          var pro = procedureList[j];
          var proColor = pro.color;
          var otherMaching = '';
          if (pro.otherMaching !== '') {
            otherMaching = pro.otherMaching;
          }

          $item.append(`
            <div style="color:${proColor};" class="procedureFont" color="${proColor}" 
              materialType="${materialType}" procedureId="${pro.procedureId}" otherMaching="${otherMaching}">
              ${page.getMaterialProText(pro)}
            </div>
          `);
        }
      }
      page.procedureSumCount = sumCount;
      $(".procedureSumCount").text(page.procedureSumCount);
      $(".materialProcedure").html($html.html());
      $("#editMaterialProcedureBtn").removeClass("hidden");
      $("#autoSchedulingBtn").removeClass("hidden");
      $("#deleteTreeBtn").removeClass("hidden");
      page.drawFlow();
      vueData.diffDay = null;
    });
    page.searchType = "query";
  },
  editMaterialProcedure: function () {
    if (vueData.pageOrderId == '') {
      layAlert("未获取到订单编号");
      return false;
    }

    ajaxUtil.ajaxRuquestNoQuan(baseUrl + 'partsProcedure/getOrderMaterial', {
      "orderId": vueData.pageOrderId
    }, function (data) {
      var html = "<option value=''>请选择</option>";
      for (var i = 0; i < data.length; i++) {
        html += "<option value='" + data[i].materialType + "'>" + data[i].materialType + "</option>";
      }
      $("#modalOrderId").html(vueData.pageOrderId);
      $("#materialType").html(html);
      $("#setCombinationModal").modal("show");
    });
  },
  getOrderMaterialProcedureHaveAndNoHave: function () {
    var materialType = $("#materialType option:selected").val();
    var orderId = $("#modalOrderId").text();
    ajaxUtil.ajaxRuquestNoQuan(baseUrl + 'partsProcedure/getOrderMaterialProcedureHaveAndNoHave', {
      "orderId": orderId,
      "materialType": materialType
    }, function (data) {
      page.modalDeptId = data.deptId;
      page.materialSort = data.materialSort;
      var processListHave = data.processListHave;
      var processListNoHave = data.processListNoHave;
      var leftHtml = "";
      var rightHtml = "";
      //右边已有的
      for (var i = 0; i < processListHave.length; i++) {
        var maching = processListHave[i].maching;
        if (maching != '') {
          maching = "-" + maching;
        }
        rightHtml += "<li class='item ui-sortable-handle'  data-id=" + processListHave[i].id + " maching='" + processListHave[i].maching +
          "'  color='" + processListHave[i].color + "'>" + processListHave[i].workshopName + "-" + processListHave[i].processName + maching +
          "</li>";
      }

      //左边没有的
      for (var i = 0; i < processListNoHave.length; i++) {
        leftHtml += "<li class='item ui-sortable-handle'  data-id=" + processListNoHave[i].id + ">" + processListNoHave[i].workshopName +
          "-" + processListNoHave[i].processName + "</li>";
      }

      $("#setCombinationModal .left-box").html(leftHtml);
      $("#setCombinationModal .right-box").html(rightHtml);
      page.leftAndRightBindSet();
    });
  },
  getOrderMaterialNoHave: function () {
    var object = new Object();
    object.deptId = page.modalDeptId;
    object.orderId = $("#modalOrderId").text();
    object.materialType = $("#materialType option:selected").val();
    object.searchWhere = $("#setSearchWhereInput").val();
    ajaxUtil.ajaxRuquest(baseUrl + "partsProcedure/getOrderMaterialNoHave", object, function (data) {
      var processListNoHave = data;
      var leftHtml = "";
      for (var i = 0; i < processListNoHave.length; i++) {
        leftHtml += "<li class='item ui-sortable-handle'  data-id=" + processListNoHave[i].id + ">" + processListNoHave[i].workshopName +
          '-' + processListNoHave[i].processName + "</li>";
      }
      $("#setCombinationModal .left-box").html(leftHtml);
      page.leftAndRightBindSet();
    });
  },
  saveUpdateProcedure: function () {
    var object = new Object();
    object.orderId = $("#modalOrderId").text();
    object.materialType = $("#materialType option:selected").val();
    var array = new Array();
    var i = 1;

    $("#setCombinationModal .right-box").find(".ui-sortable-handle").each(function () {
      var pro = new Object();
      pro.id = $(this).attr("data-id");
      pro.otherMaching = $(this).attr("maching");
      pro.maching = object.materialType;
      pro.materialSort = page.materialSort;
      pro.color = $(this).attr("color");
      pro.sort = i;
      array.push(pro);
      i++;
    });
    if (array.length <= 0) {
      layAlert("请选择工序");
      return false;
    }
    object.procedureArray = JSON.stringify(array);
    ajaxUtil.ajaxRuquest(baseUrl + "partsProcedure/saveUpdateProcedure", object, function (data) {
      layer.msg(data, {
        icon: 1
      });
      $("#setCombinationModal").modal("hide");
      page.getAlreadySaveProcedure(object.orderId);
      vueData.diffDay = null;
    });
  },
  leftAndRightBindSet: function () {
    $("#setCombinationModal .item").unbind("click");
    $("#setCombinationModal .left-box .item").unbind("dblclick");
    $("#setCombinationModal .right-box .item").unbind("dblclick");
    //单击
    $("#setCombinationModal .item").bind("click", function () {
      $(this).toggleClass("selected-item");
    });

    //左边双击右移
    $("#setCombinationModal .left-box .item").bind("dblclick", function () {
      $("#setCombinationModal .right-box").append($(this).removeClass('selected-item'));
      page.leftAndRightBindSet();
    });

    //右边双击左移
    $("#setCombinationModal .right-box .item").bind("dblclick", function () {
      $("#setCombinationModal .left-box").append($(this).removeClass('selected-item'));
      page.leftAndRightBindSet();
    });
  },
  removeBtnBind: function () {
    $("#setCombinationModal .add-one").bind("click", function () {
      $("#setCombinationModal .right-box").append($("#setCombinationModal .left-box").find('.selected-item').removeClass('selected-item'));
    });

    $("#setCombinationModal .add-all").bind("click", function () {
      $("#setCombinationModal .right-box").append($("#setCombinationModal .left-box").find('.item').removeClass('selected-item'));
    });

    $("#setCombinationModal .remove-one").bind("click", function () {
      $("#setCombinationModal .left-box").append($("#setCombinationModal .right-box").find('.selected-item').removeClass('selected-item'));
    });

    $("#setCombinationModal .remove-all").bind("click", function () {
      $("#setCombinationModal .left-box").append($("#setCombinationModal .right-box").find('.item').removeClass('selected-item'));
    });
  },
  //工序移动排序
  remove: function () {
    $('.item-box').sortable({
      placeholder: 'item-placeholder',
      connectWith: '.item-box',
      revert: true
    }).droppable({
      accept: '.item',
      hoverClass: 'item-box-hover',
      drop: function (event, ui) {
        setTimeout(function () {
          ui.draggable.removeClass('selected-item');
        }, 500);
      }
    }).disableSelection();
  },
  drawFlow: function (type) {
    var $content = $('.pro-content');
    var $pro = $content.find('.materialProcedure');

    var $proItems = $pro.find('.pro-item');
    var proItems = [];
    var startIndex = type === 'schedul' ? 3 : 0;
    var startTitle = type === 'schedul' ? 2 : 0;
    for (var i = 0; i < $proItems.length; i++) {
      var $proItem = $($proItems[i]);
      var $processes = $proItem.find('>div');
      var $proTitle = $($processes[startTitle]);
      var obj = {
        color: $proTitle.attr('color'),
        $titleEl: $proTitle,
        index: i
      };

      var processList = [];
      var len = $processes.length;
      for (var j = startIndex; j < len; j++) {
        var $process = $($processes[j]);
        if (j === len - 1) {
          obj.$lastEl = $process;
        }
        if (j === 0) {
          continue;
        }

        var processObj = {
          color: $process.attr('color'),
          $el: $process
        };
        var otherMaching = $process.attr('othermaching');
        if (otherMaching !== '') {
          processObj.otherMaching = otherMaching;
        }
        processList.push(processObj);
      }
      obj.processList = processList;
      proItems.push(obj);
    }

    var drawItems = this.getDrawItems(proItems);
    var $flow = $content.find('.materialFlow');
    var width = $pro.width()
    var height = $pro.height();
    $flow.attr('width', width);
    $flow.attr('height', height);
    this.drawFlowLine($flow[0], drawItems, width, height);
  },

  getDrawItems: function (proItems) {
    var drawItems = [];
    var self = this;
    for (var i = proItems.length - 2; i >= 0; i--) {
      var proItem = proItems[i];
      var processList = proItem.processList;
      var usedColor = [];
      for (var j = 0; j < processList.length; j += addIndex) {
        var processObj = processList[j];
        var color = processObj.color;
        var option = this.checkCanDraw(processList, j, usedColor);
        var addIndex = option.sameProcessLength;

        if (!option.canDraw) {
          continue;
        }

        var sameIndex = _.findIndex(proItems, function (obj, index) {
          if (index <= i) {
            return false;
          }
          return obj.color === color;
        });
        if (sameIndex === -1) {
          continue;
        }
        var sameItem = proItems[sameIndex];
        var $to = processObj.$el;
        var $form = sameItem.$lastEl;

        var rangeItems = proItems.slice(i + 1, sameIndex + 1);
        var maxRangeItem = _.maxBy(rangeItems, function (item) {
          return self.getElTop(item.$lastEl);
        });

        var hasSame;
        if (sameIndex === i + 1) {
          hasSame = false;
        } else {
          hasSame = maxRangeItem.index === sameIndex;
        }

        var top = this.getElTop(maxRangeItem.$lastEl);
        var toTop = this.getElTop($to);
        var sameTop = undefined;
        if (hasSame) {
          if (top > toTop) {
            sameTop = top;
          }
        } else {
          if (top >= toTop) {
            sameTop = top + maxRangeItem.$lastEl.height();
          }
        }

        if (sameTop !== undefined) {
          if (sameTop - toTop > 0) {
            $to.css('margin-top', `${sameTop - toTop}px`);
            $to.addClass('has-same-process');
            var $formProcess;
            if (j === 0) {
              $formProcess = proItem.$titleEl;
            } else {
              $formProcess = processList[j - 1].$el;
            }
            drawItems.push({
              form: $formProcess,
              to: $to,
              type: 'process'
            });
          }
        }

        drawItems.push({
          form: $form,
          to: $to,
          type: 'item'
        });
      }
    }
    return drawItems;
  },

  checkCanDraw: function (processList, index, usedColor) {
    var color = processList[index].color;
    var processes = [];

    for (var i = index; i < processList.length; i++) {
      var processObj = processList[i];
      if (color === processObj.color) {
        processes.push(processObj);
      } else {
        break;
      }
    }

    var processObj = _.find(processes, function (obj) {
      var otherMaching = obj.otherMaching;
      return otherMaching && otherMaching !== '';
    });
    var canDraw;
    if (processObj !== undefined) {
      canDraw = true;
    } else {
      if (usedColor.indexOf(color) === -1) {
        canDraw = true;
      } else {
        canDraw = false;
      }
    }

    if (canDraw) {
      if (processes[0].otherMaching === undefined) {
        usedColor.push(color);
      }
    }

    return {
      sameProcessLength: processes.length,
      canDraw: canDraw
    };
  },

  drawFlowLine: function (el, drawItems, width, height) {
    var ctx = el.getContext("2d");
    ctx.lineWidth = "2";
    ctx.clearRect(0, 0, width, height);
    for (var i = 0; i < drawItems.length; i++) {
      var drawItem = drawItems[i];
      this.drawLineArrow(ctx, drawItem);
    }
  },

  drawLineArrow: function (ctx, drawItem) {
    var form = drawItem.form;
    var formX = form.position().left;
    var formY = this.getElTop(form);
    var to = drawItem.to;
    var toX = to.position().left;
    var toY = this.getElTop(to);

    var type = drawItem.type;
    var arrawDirection;

    switch (type) {
      case 'item': {
        arrawDirection = 'left';
        if (formY === toY) {
          formY += form.outerHeight() / 2;
          toY += to.outerHeight() / 2;
          toX += to.outerWidth();
        } else {
          formX += form.outerWidth() / 2;
          formY += form.outerHeight();
          toX += to.outerWidth();
          toY += to.outerHeight() / 2;
        }
        break;
      }
      case 'process': {
        arrawDirection = 'bottom';
        formX += form.outerWidth() / 2;
        formY += form.outerHeight();
        toX += to.outerWidth() / 2;
        break;
      }
    }
    formX = _.round(formX, 0);
    formY = _.round(formY, 0);
    toX = _.round(toX, 0);
    toY = _.round(toY, 0);
    if (arrawDirection !== undefined) {
      ctx.beginPath();
      ctx.moveTo(formX, formY);
      if (formX === toX || formY === toY) {
        ctx.lineTo(toX, toY);
      } else {
        ctx.lineTo(formX, toY);
        ctx.lineTo(toX, toY);
      }
      this.drawArrow(ctx, toX, toY, arrawDirection);
      ctx.stroke();
    }
  },

  drawArrow: function (ctx, x, y, direction) {
    var startX, startY, endX, endY;
    switch (direction) {
      case 'left':
        x += 1;
        startX = endX = x + 10;
        startY = y - 7;
        endY = y + 7;
        break;

      case 'bottom':
        y -= 1;
        startY = endY = y - 10;
        startX = x - 7;
        endX = x + 7;
        break;
    }
    ctx.moveTo(startX, startY);
    ctx.lineTo(x, y);
    ctx.lineTo(endX, endY);
  },

  clearCanvas: function () {
    var $content = $('.pro-content');
    var $pro = $content.find('.materialProcedure');
    var $flow = $content.find('.materialFlow');
    var width = $pro.width()
    var height = $pro.height();
    $flow.attr('width', width);
    $flow.attr('height', height);
    var ctx = $flow[0].getContext("2d");
    ctx.lineWidth = "2";
    ctx.clearRect(0, 0, width, height);
  },

  getElTop: function ($el) {
    var marginTop = $el.outerHeight(true) - $el.outerHeight();
    var top = $el.position().top;
    return top + marginTop;
  }
}

/**
 * 排期
 */
var scheduling = {
  bind: function () {
    $("#autoSchedulingBtn").bind("click", function () {
      scheduling.autoScheduling();
    });
  },
  autoScheduling: function () {
    var self = this;
    ajaxUtil.ajaxRuquest(baseUrl + "partsProcedure/getOrderMaterialParchaseAndInCountTime", {
      'orderId': vueData.pageOrderId
    }, function (purchaseAndInData) {
      page.clearCanvas();
      var data = page.aleradySaveData;
      if (data.length <= 0) {
        layAlert("该订单没有设置工序");
        return false;
      }
      /**
       * 循环遍历物料类型
       */
      var sumCount = 0;
      var $html = $('<div></div>');
      var schedulTimeList = [];
      for (var i = 0; i < data.length; i++) {
        var obj = data[i];
        var procedureList = obj.procedureList;
        var materialType = obj.materialType;
        var color = procedureList[0].color;
        var dayTime = procedureList[0].dailyWorkingHours == 0.0 ? 28800 : procedureList[0].dailyWorkingHours * 60 * 60;
        var $item = $('<div class="pro-item"></div>');
        $html.append($item);

        $item.append(`
              <div class="item-title material" style="color:${color};" materialType="${materialType}" color="${color}">
                <span>${materialType}</span>
                <span>${procedureList.length}</span>
              </div>
            `);

        sumCount = sumCount + procedureList.length;
        /**获取最后一道有时间的工序（按工序的顺序）的顺序**/
        var filterProcedure = _.filter(procedureList, function (o) {
          return o.maxTime != '';
        });
        //如果该物料还未开始生产
        var timeSort = 1000000;
        var time = "";
        if (filterProcedure.length > 0) {
          timeSort = filterProcedure[filterProcedure.length - 1].sort;
        }
        var sumTimes = 0;

        /**
         * 判断采购入库的情况
         */
        if (purchaseAndInData != null && purchaseAndInData.length > 0) { //采购入库都没有
          var array = _.filter(purchaseAndInData, function (o) {
            return o.materialType != null && o.materialType != '';
          });
          if (array.length <= 0) { //如果改物料没有采购和入库
            $item.append(`
                <div style="color:${color};" class="procedureFont" color="${color}">
                       采购
                </div>
                <div style="color:${color};" class="procedureFont" color="${color}">
                      入库
                </div>
            `);
          } else { //有采购入库信息
            //设置采购时间
            var dd = array[0];
            schedulTimeList.push(dd.laterPhase);
            $item.append(`
                <div style="color:${color};" class="procedureFont" color="${color}">
                     采购:  &nbsp;&nbsp;<span style='color:green; float:right;'>${dd.laterPhase.substring(5,11)}
                </div>
            `);
            //如果有入库，设置入库时间
            if (dd.inTime != null && dd.inTime != '') {
              schedulTimeList.push(dd.inTime);
              $item.append(`
                  <div style="color:${color};" class="procedureFont" color="${color}">
                           入库:  &nbsp;&nbsp;<span style='color:green; float:right;'>${dd.inTime.substring(5,11)}
                  </div>
              `);
            } else { //如果没有入库时间，则预计复期入库
              schedulTimeList.push(dd.laterPhase);
              $item.append(`
                  <div style="color:${color};" class="procedureFont" color="${color}">
                           入库:  &nbsp;&nbsp;<span style='color:red; float:right;'>${dd.laterPhase.substring(5,11)}
                  </div>
              `);

              /**
               * 如果还未开始生产，则预计生产时间
               */
              if (filterProcedure.length <= 0) {
                timeSort = -1;
                var dff = moment(dd.laterPhase.substring(0, 11)).diff(moment(echartUtil.GetDateStr(0)), 'day');
                if (dff > 0) {
                  sumTimes = sumTimes + dff * dayTime;
                }
              }
            }
          }
        } else {
          $item.append(`
              <div style="color:${color};" class="procedureFont" color="${color}">
                     采购
              </div>
              <div style="color:${color};" class="procedureFont" color="${color}">
                    入库
              </div>
          `);
        }


        var beforeTime = "";
        for (var j = 0; j < procedureList.length; j++) {

          var pro = procedureList[j];
          var proColor = pro.color;
          var otherMaching = '';
          if (pro.otherMaching !== '') {
            otherMaching = pro.otherMaching;
          }

          var color = 'green';
          var maxTime = "";
          //当本道工序就是最后一道报工顺序的时候，时间显示为本道工序最后报工时间
          if (pro.sort <= timeSort) {
            maxTime = pro.maxTime;
          }
          //当本工序在最后报工工序之后的时候
          if (pro.sort > timeSort) {
            var procedureTime = 0;
            if (pro.processingObject == '款' || pro.changeUnit == '款' || pro.timeUnit == '款') { //如果是调机，只算一次
              procedureTime = pro.procedureWorkTime;
            } else { //否则为订单数*工序作业时间
              procedureTime = pro.procedureWorkTime * pro.orderCount;
            }
            //加上交接时间20分钟(1200秒)
            procedureTime = procedureTime + 1200;
            sumTimes = sumTimes + procedureTime;
            var day = Math.floor(sumTimes / dayTime);
            maxTime = echartUtil.GetDateStr(day);
            var restType = pro.restType;
            if (beforeTime == "" || moment(echartUtil.GetDateStr(0)).diff(moment(beforeTime), 'day') >= 0) {
              beforeTime = echartUtil.GetDateStr(0);
            }
            var dayArray = scheduling.getBetweenDateStr(beforeTime, maxTime);
            var addDay = scheduling.getMonthWorkDay(restType, dayArray);
            if (addDay > 0) {
              if (addDay % 1 == 0) {
                sumTimes = sumTimes + addDay * dayTime;
                day = day + addDay;
                maxTime = echartUtil.GetDateStr(day);
              } else {
                sumTimes = sumTimes + dayTime / 2 + (addDay - 1) * dayTime;
                day = Math.floor(sumTimes / dayTime);
                maxTime = echartUtil.GetDateStr(day);
              }
            }
            dayArray = [];
            dayArray.push(maxTime);
            var restDay = scheduling.getMonthWorkDay(restType, dayArray);

            if (restDay == 1) {
              //时间加一天
              sumTimes = sumTimes + dayTime;
              maxTime = echartUtil.GetDateStr(day + 1);
              dayArray = [];
              dayArray.push(maxTime);
              //判断时间加一天是否
              restDay = scheduling.getMonthWorkDay(restType, dayArray);
              //如果是休息
              if (restDay == 1) {
                //时间再加一天
                sumTimes = sumTimes + dayTime;
                maxTime = echartUtil.GetDateStr(day + 1);
              }
            } else if (restDay == 0.5) {
              //时间加半天
              sumTimes = sumTimes + dayTime / 2;
              //判断加半天之后时候跨天
              var xx = Math.floor(sumTimes / dayTime);
              if (xx != day) {
                //时间为加半天之后的日期
                maxTime = echartUtil.GetDateStr(xx);
                dayArray = [];
                dayArray.push(maxTime);
                //判断时间加一天是否
                restDay = scheduling.getMonthWorkDay(restType, dayArray);
                if (restDay == 1) {
                  sumTimes = sumTimes + dayTime;
                  maxTime = echartUtil.GetDateStr(day + 1);
                }
              }
            }
            color = 'red';
          }
          beforeTime = maxTime;

          if (maxTime !== '') {
            schedulTimeList.push(maxTime);
          }
          $item.append(`
              <div style="color:${proColor};" class="procedureFont" color="${proColor}" 
                materialType="${materialType}" procedureId="${pro.procedureId}" otherMaching="${otherMaching}">
                ${page.getMaterialProText(pro)}&nbsp;<span style='color:${color};'>${maxTime.substring(5,11)}</span> 
              </div>
            `);
        }
      }
      page.procedureSumCount = sumCount;
      $(".procedureSumCount").text(page.procedureSumCount);
      $(".materialProcedure").html($html.html());
      page.drawFlow('schedul');
      var diffDay = self.calDiffDay(schedulTimeList);
      vueData.diffDay = diffDay;
    });
  },

  calDiffDay: function (timeList) {
    if (timeList.length <= 1) {
      return 0;
    }

    timeList = _.orderBy(timeList);
    var minTime = moment(timeList[0]).startOf('day');
    var maxTime = moment(timeList[timeList.length - 1]).startOf('day');
    var diffDay = maxTime.diff(minTime, 'day');
    return diffDay;
  },
  /*
   * 获取两日期之间的所有日期
   */
  getBetweenDateStr: function (start, end) {
    var result = [];
    var startMoment = moment(start);
    var endMoment = moment(end);
    while (startMoment.isSameOrBefore(endMoment, 'day')) {
      result.push(startMoment.format('YYYY-MM-DD'));
      startMoment.add(1, 'day');
    }
    return result;
  },
  /**
   * 根据休息类型和日期判断当天是否休息
   */
  getMonthWorkDay: function (restType, days) {
    var restDay = 0; //该区间休息天数
    switch (restType) {
      case 0:
        restDay = 0;
        break; //月休0填
      case 1: //月休一天，默认初一休息
        //如果含有初一，则休息一天
        _.forEach(days, function (day) {
          if (Number(day.substring(8, 10)) == 1) {
            restDay = restDay + 1;
          }
        });
        break;
      case 2: //月休两天
        //如果含有初一，或者含有15，则休息一天
        _.forEach(days, function (day) {
          if (Number(day.substring(8, 10)) == 1 || Number(day.substring(8, 10)) == 15) {
            restDay = restDay + 1;
          }
        });
        break;
      case 3: //月休三天
        //如果含有初一，或者含有10号，20号，则休息一天
        _.forEach(days, function (day) {
          if (Number(day.substring(8, 10)) == 1 || Number(day.substring(8, 10)) == 10 || Number(day.substring(8, 10)) == 20) {
            restDay = restDay + 1;
          }
        });
        break;
      case 4: //周休一天
        //周天休息一天
        _.forEach(days, function (day) {
          if (moment(day).day() == 0) {
            restDay = restDay + 1;
          }
        });
        break;
      case 5: //周休1.5天
        //周天休息一天，周六休息半天
        _.forEach(days, function (day) {
          if (moment(day).day() == 0) {
            restDay = restDay + 1;
          }
          if (moment(day).day() == 6) {
            restDay = restDay + 0.5;
          }
        });
        break;
      case 6: //周休2天
        //周天，周六休息一天
        _.forEach(days, function (day) {
          if (moment(day).day() == 0 || moment(day).day() == 6) {
            restDay = restDay + 1;
          }
        });
        break;
    }
    return restDay;
  }
}



var config = {
  //		colorArray:['Blue','#8B2500','LightPink','Crimson','Purple','SkyBlue','Aqua','Green','LawnGreen','#FF6EB4','GoldEnrod','#B23AEE','OrangeRed','LightGreen', '#8B0000','#AB82FF','#FFBBFF','#FF34B3','#CD1076','#FFE7BA','#FFEC8B','#53868B','#6495ED','#ADFF2F','#F5F5DC','#A020F0','#C6E2FF','#7A8B8B']
  colorArray: ['rgb(0,0,0)', 'rgb(43,108,40)', 'rgb(152,32,15)', 'rgb(47,117,181)', 'rgb(56,152,14)', 'rgb(112,48,160)', 'rgb(91,155,213)',
    'rgb(237,125,49)', 'rgb(123,123,123)', 'rgb(192,0,0)', 'rgb(30,30,30)', 'rgb(38,103,37)', 'rgb(225,30,13)', 'rgb(40,112,225)',
    'rgb(50,175,25)', 'rgb(195,48,130)', 'rgb(85,150,205)', 'rgb(245,100,45)', 'rgb(40,40,80)', 'rgb(255,0,0)', 'rgb(0,255,0)', 'rgb(0,0,255)',
    'rgb(200,25,10)', 'rgb(35,108,210)', 'rgb(45,195,35)', 'rgb(465,90,145)', 'rgb(70,145,215)', 'rgb(45,225,150)', 'rgb(180,180,180)',
    'rgb(50,50,50)', 'rgb(0,139,69)'
  ]
}

var app = new Vue({
  el: '#order-app',
  data: function () {
    return vueData;
  },

  created: function () {
    this.loading = true;
    var self = this;
    ajaxUtil.ajaxRuquestNoQuan(baseUrl + 'companyMaterial/getAllOrderSearchWhere', null, function (orderList) {
      self.orderList = orderList;
      self.loading = false;
    });
  },

  methods: {
    filterOrderId: function (options, queryValue) {
      if (queryValue === '') {
        return options;
      }

      queryValue = queryValue.toLowerCase();
      var filterParams = this.filterParams;
      options = _.filter(options, function (option) {
        for (var i = 0; i < filterParams.length; i++) {
          var filterParam = filterParams[i];
          var value = _.get(option, filterParam, '');
          if (value === null) {
            value = '';
          }
          if (typeof value === 'string') {
            value = value.toLowerCase();
          }
          if (value.indexOf(queryValue) !== -1) {
            return true;
          }
        }
        return false;
      });
      return options;
    }
  },

  components: {
    PageSelect: PageSelect
  }
});
